package com.netease.nimlib.ipc.cp.data;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * 基于SharedPreference的数据处理器
 * 这里不处理void类型，交给子类自行定制事件处理器
 * <p>
 * Created by huangjun on 2017/10/31.
 */
public abstract class PreferenceDataHandler extends IDataHandler {

    protected PreferenceDataHandler(Context context, String name) {
        super(context, name);
    }

    @Override
    public boolean hasKey(final String key) {
        return context.getSharedPreferences(name, Context.MODE_PRIVATE).contains(key);
    }

    @Override
    public String onQueryString(final String key, final String defaultValue) {
        return getSP().getString(key, defaultValue);
    }

    @Override
    public void onHandleString(final String key, final String value) {
        getSP().edit().putString(key, value).apply();
    }

    @Override
    public boolean onQueryBoolean(final String key, final boolean defaultValue) {
        return getSP().getBoolean(key, defaultValue);
    }

    @Override
    public void onHandleBoolean(final String key, final boolean value) {
        getSP().edit().putBoolean(key, value).apply();
    }

    @Override
    public void onHandleInt(final String key, final int value) {
        getSP().edit().putInt(key, value).apply();
    }

    @Override
    public int onQueryInt(final String key, final int defaultValue) {
        return getSP().getInt(key, defaultValue);
    }

    @Override
    public void onHandleFloat(final String key, final float value) {
        getSP().edit().putFloat(key, value).apply();
    }

    @Override
    public float onQueryFloat(final String key, final float defaultValue) {
        return getSP().getFloat(key, defaultValue);
    }

    @Override
    public void onHandleLong(final String key, final long value) {
        getSP().edit().putLong(key, value).apply();
    }

    @Override
    public long onQueryLong(final String key, final long defaultValue) {
        return getSP().getLong(key, defaultValue);
    }

    @Override
    public void onRemoveKey(final String key) {
        getSP().edit().remove(key).apply();
    }

    private SharedPreferences getSP() {
        return context.getSharedPreferences(name, Context.MODE_PRIVATE);
    }
}
